package com.yra.config;

import com.yra.filter.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ValidateCodeFilter validateCodeFilter;
    @Autowired
    private MyAuthenticationSucessHandler authenticationSucessHandler;
    @Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class).
                formLogin() // 表单方式
//        http.httpBasic() // HTTP Basic方式
                 .loginPage("/manager/login")
                 .loginProcessingUrl("/login")
                 .successHandler(authenticationSucessHandler) // 处理登录成功
                 .failureHandler(authenticationFailureHandler) // 处理登录失败
                .and()
                .logout()
                .logoutUrl("/manager/signout")
                .logoutSuccessUrl("/")
                .and()
                .authorizeRequests() // 授权配置
//                  .regexMatchers("/manager").permitAll()
                .antMatchers().hasRole("USER")
//                .antMatchers("/manager/login").hasRole("ADMIN")
                 .antMatchers("/upload/**","/manager/login","/**/dist/**","/**/plugins/**","/","/index","/**/**.js","/mall/**","/**/fonts/**","/product/**","/user/**","/search","/common/**","/shopcart/**").permitAll()
                .anyRequest()  // 所有请求
                .authenticated()
                 .and().csrf().disable()
                .headers().frameOptions().sameOrigin(); // 都需要认证

//        http.formLogin().loginPage("")
    }
}